//删除的id
var delId = [];
//	时间初试化
$('#startTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#endTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#deliverDateStr').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#arriveDateStr').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});


var oprateUrl = DOMAIN + '/purchase/queryPurchaseList' + isLogin;
function loadTable() {
	$("#table").bootstrapTable({ // 对应table标签的id
		url: oprateUrl,
		method: 'get',
		cache: false,
		striped: true,
		pagination: true,
		pageSize: 50,
		pageNumber: 1,
		pageList: [50,100],
		search: false,
		showColumns: false,
		clickToSelect: true,
		queryParams: {
			deleteFlg: 0
		},
		smartDisplay: false,
		columns: [{
			field: "id",
			title: "id",
			align: "center",
			valign: "middle",
			sortable: "true",
			visible: false
		}, {
			field: "orderNo",
			title: "采购订单号",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "name",
			title: "供应商",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "address",
			title: "供货地址",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "deliverDateStr",
			title: "下单时间",
			align: "center",
			valign: "middle",
			sortable: "true"
		} ,{
			field: "deliverDateStr",
			title: "发货时间",
			align: "center",
			valign: "middle",
			sortable: "true"
		} ,{
			field: "arriveDateStr",
			title: "预计到达时间",
			align: "center",
			valign: "middle",
			sortable: "true"
		} ,{
			field: "createUser",
			title: "创建人",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "createTimeStr",
			title: "创建时间",
			align: "center",
			valign: "middle",
			sortable: "true"
		} ,{
			field: "statuses",
			title: "订单状态",
			align: "center",
			valign: "middle",
			sortable: "true"
		} ,{
			field: "",
			title: "操作",
			align: "center",
			valign: "middle",
			events: funOprate,
			formatter: function (value, row, index) {
	
				if (row.deleteFlg == 1) {
					return '<button status="' +row.statuses + '"  orderNo="' + row.orderNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="EditInfo(this)" class="btn btn-primary btn-sm edit">编辑</button>';
				}if(row.statuses == '已确认'){
					return '<button onclick="lookInfo(this)"  orderNo="' + row.orderNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal"  class="btn btn-primary btn-sm edit">&emsp;查看</button>  '
				}if(row.statuses == '启用'){
					return '<button onclick="EditInfo(this)"  orderNo="' + row.orderNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal"  class="btn btn-primary btn-sm edit">&emsp;编辑</button> <button orderNo="' +
						row.orderNo + '"onclick="sureInfo(this)"  class="btn btn-primary btn-sm">&emsp;确认订单</button> <button onclick="collbakeInfo(this)"  orderNo="' + row.orderNo + '" type="button" data-toggle="modal" class="btn btn-primary btn-sm edit">&emsp;撤销</button>'
				} else{
					return '<button onclick="lookInfo(this)"  orderNo="' + row.orderNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal"  class="btn btn-primary btn-sm edit">&emsp;查看</button>  '
				}
			}
		}],
		//>>>>>>>>>>>>>>导出excel表格设置
		showExport: true,
		showExport: true,
		//是否显示导出按钮
		buttonsAlign: "left",
		//按钮位置
		exportDataType: 'all',
		//导出的方式 all全部 selected已选择的  basic', 'all', 'selected'.
		Icons: 'glyphicon glyphicon-export',
		exportTypes: ['excel', 'doc', 'xlsx', 'txt',],
		//导出文件类型
		exportOptions: {
			ignoreColumn: [0, 0],  //忽略某一列的索引，id删除更新用用，不显示与导出

			fileName: '导出数据表',
			//文件名称设置
			worksheetName: 'sheet1',
			//表格工作区名称
			tableName: '导出数据表',
			// excelstyles: ['background-color', 'color', 'font-size', 'font-weight'], 设置格式

		},
		//导出excel表格设置<<<<<<<<<<<<<<<<
		formatNoMatches: function () {
			return '没有找到匹配的记录';
		}
	});
	function queryParams(params) {
		var params = {};
		return params;
	};
}

// document.body.onclick = function() {
//      var rows = $('#tableAddDetail').bootstrapTable('getData');
// 	 var allmoney = 0;
// 	 	for (var i = 0;i<rows.length;i++) {
// 	 		allmoney += rows[i].money; 
// 	 	}	
// 	 allmoney = allmoney.toFixed(2);
// 	 allmoney = allmoney.toString();
// 	 document.getElementById("moneynum").innerHTML=allmoney;
// }
//查询
$("#selectPurchaseBtn").click(function () {
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.startTime = $("#startTime").val();
		params.endTime = $("#endTime").val();
		// params.purchaseCompany = $("#purchaseCompany").val();
		params.statuses = $("#status option:checked").val();
		return params;
	};
	var url =DOMAIN + '/purchase/queryPurchaseList' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
})

$("#tableAddDetail").bootstrapTable({ // 对应table标签的id
	url: "",
	method: 'get',
	cache: false,
	striped: true,
	pagination: true,
	pageSize: 200,
	pageNumber: 1,
	pageList: [200, 500],
	ajaxOptions: {
	               async: false // 如果设置为异步，需要等请求成功后才会生成下面的tr和td，就无法在td中添加按钮
	           },
	search: false,
	showColumns: false,
	clickToSelect: true,
	queryParams: queryParams,
	smartDisplay: false,
	columns: [{
		checkbox: true
	},
	{
		field: "id",
		title: "id",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	},
	{
		field: "pid",
		title: "序号",
		align: "center",
		valign: "middle",
		sortable: "true"
	},{
			field: "proname",
			title: "商品名称",
			align: "center",
			valign: "middle",
			sortable: "true"
		},
		{
			field: "planAmount",
			title: "计划采购量",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "completed",
			title: "已完成量",
			align: "center",
			valign: "middle",
			sortable: "true"

		},{
			field: "surplusAmount",
			title: "剩余采购量",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
				row.surplusAmount = row.planAmount-row.completed;
				if(row.surplusAmount<0){
					row.surplusAmount=0;
				}			
	              return row.surplusAmount.toFixed(2);
			}
		},{
			field: "amount",
			title: "实际采购量",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
				if(isEmpty(row.amount)){
					row.amount = row.planAmount-row.completed;
					if(row.amount<0){
						row.amount=0;
					}	
				}
				return row.amount;
			},
			cellStyle:function(value,row,index){
				return {css:{"color":"#0088cc"}} 
			}
		},
		{
			field: "price",
			title: "价格",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
				if(isEmpty(row.price)){
					row.price = 0;
				}
				return row.price;
			},
			cellStyle:function(value,row,index){
				return {css:{"color":"#0088cc"}} 
			}
		},
		{
			field: "money",
			title: "总金额",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
					row.money=row.amount*row.price;
				return row.money.toFixed(2);
			}
		} ],
	formatNoMatches: function () {
		return '';
	},
	onClickCell: function(field, value, row, $element) {
		if(field=="amount" || field=="price"){
			$element.attr('contenteditable', true);
	   		$element.blur(function() {
	   			if($element.html()=="" || isNaN($element.html())){
	   					$element.html(value);
	   			}else{
	   				var index = $element.parent().data('index');
	        		var tdValue = $element.html();
	        		saveData(index, field, tdValue,row);
	   			}
	   		});
		}
	}
});


$("#tableAddChoose").bootstrapTable({ // 对应table标签的id
	url: "",
	method: 'get',
	cache: false,
	striped: true,
	pagination: true,
	pageSize: 200,
	pageNumber: 1,
	pageList: [200, 500],
	search: false,
	ajaxOptions: {
	               async: false // 如果设置为异步，需要等请求成功后才会生成下面的tr和td，就无法在td中添加按钮
	           },
	showColumns: false,
	clickToSelect: true,
	queryParams: queryParams,
	smartDisplay: false,
	columns: [{
		checkbox: true
	},
	{
		field: "id",
		title: "id",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	},
	{
		field: "pid",
		title: "序号",
		align: "center",
		valign: "middle",
		sortable: "true"
	},{
			field: "proname",
			title: "商品名称",
			align: "center",
			valign: "middle",
			sortable: "true"
		},
		{
			field: "planAmount",
			title: "计划采购量",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "completed",
			title: "已完成量",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "surplusAmount",
			title: "剩余采购量",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
				row.surplusAmount = row.planAmount-row.completed;
				if(row.surplusAmount<0){
					row.surplusAmount=0;
				}			
	              return row.surplusAmount.toFixed(2);
			}
		}/*,{
			field: "amount",
			title: "实际采购量",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
				if(isEmpty(row.amount)){
					row.amount = row.planAmount-row.completed;
					if(row.amount<0){
						row.amount=0;
					}	
				}
				return row.amount;
			},
			cellStyle:function(value,row,index){
				return {css:{"color":"#0088cc"}} 
			}
		},
		{
			field: "price",
			title: "价格",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
				if(isEmpty(row.price)){
					row.price = row.price;
				}
				return row.price;
			},
			cellStyle:function(value,row,index){
				return {css:{"color":"#0088cc"}} 
			}
		}*/,
		{
			field: "money",
			title: "总金额",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
					row.money=row.amount*row.price;
				return row.money.toFixed(2);
			}
		} ],
	formatNoMatches: function () {
		return '';
	}/*,
	onClickCell: function(field, value, row, $element) {
		if(field=="amount" || field=="price"){
			$element.attr('contenteditable', true);
	   		$element.blur(function() {
	   			if($element.html()=="" || isNaN($element.html())){
	   					$element.html(value);
	   			}else{
	   				let index = $element.parent().data('index');
	        		let tdValue = $element.html();
	        		saveData(index, field, tdValue,row);
	   			}
	   		});
		}
	}*/
});

 function saveData(index, field, value,row) {
		 var rows = $('#tableAddDetail').bootstrapTable('getData');
		 var allmoney = 0;
			for (var i = 0;i<rows.length;i++) {
				allmoney += rows[i].money; 
			}	
		 allmoney = allmoney.toFixed(2);
		 allmoney = allmoney.toString();
		 document.getElementById("moneynum").innerHTML=allmoney;
       $("#tableAddDetail").bootstrapTable('updateCell', {
            index: index,       
            field: field,       //列名
            value: value        //cell值
        });
		$("#tableAddDetail").bootstrapTable('updateCell', {
		     index: index,       
		     field: 'money',       //列名
		     value: (row.amount*row.price).toFixed(2)		 //cell值
		 });
		 
		// var rows = $('#tableAddDetail').bootstrapTable('getData');
		// var allmoney = 0;
		// 	for (var i = 0;i<rows.length;i++) {
		// 		allmoney += rows[i].money; 
		// 	}	
		// allmoney = allmoney.toFixed(2);
		// allmoney = allmoney.toString();
		// document.getElementById("moneynum").innerHTML=allmoney;
		
		/* id = row.id;
		amount = value;
		price = row.price;
		$.ajax({
			type: "patch",
			url: DOMAIN + '/purchase/updatePurInfo/' + isLogin+'&id=' + id+'&amount=' + amount+'&price=' + price,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function () {
				alert('编辑失败');
			},
			complete: function () {
			}
		});*/
} 
function queryParams(params) {
	return params;
};

//新增按钮，不存到数据库
$("#AddPur-insertBtn").click(function () {

	//获取数据
	var productCode = $('#productCode').val();
	var productName = $('#productName').val();
	//判断商品是否已在明细中
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	for (var i = 0; i < rows.length; i++) {
		if (rows[i].productCode == productCode) {
			alert("商品" + productName + "已经存在，请输入其他商品");
			return;
		}
	}
	var name = $('#names').val();
	var deliverDateStr = $('#deliverDateStr').val();
	var arriveDateStr = $('#arriveDateStr').val();
	var productType = $('#productType').val();
	var specifications = $('#specifications').val();
	var grade = $('#grade').val();
	var units = $('#units').val();
	var amount = $('#amount').val();
	var price = $('#price').val();
	var priceType = $('#priceType').val();
	var roughWeight = $('#roughWeight').val();
	var suttle = $('#suttle').val();
	var comments = $('#comments').val();
	var money = $('#money').val();
	var planNo = $('#BigPlanNo').val();
	var count = $('#tableAddDetail').bootstrapTable('getData').length;
	var options = $("#tableAddDetail").bootstrapTable('getOptions');
	var pid = options.pageSize * (options.pageNumber - 1) + Number(count) + 1;
	//var t = $('#info').serializeArray();
	var t = getFormJsonObject($("#info"));
	var flag = false;
	var flag = isInfoNull(t);
	if (!flag) {
		return;
	}
	$('#tableAddDetail').bootstrapTable('insertRow', {
		index: count,
		row: {
			pid: pid,
			proname: productName,
			planNo: planNo,
			name:name,
			deliverDateStr:deliverDateStr,
			arriveDateStr:arriveDateStr,
			productCode: productCode,
			productType: productType,
			specifications: specifications,
			grade: grade,
			units: units,
			price: price,
			priceType: priceType,
			amount: amount,
			roughWeight: roughWeight,
			suttle: suttle,
			comments: comments,
			money:money
		}
	});
	//新增后置空
	$('#productCode').val('');
	$('#productName').val('');
	$('#productType').val('');
	$('#specifications').val('');
	$('#grade').val('');
	$('#units').val('');
});



//弹窗新增按钮，存到上一层
$("#SurePur-saveBtn").click(function () {
	var rows = $('#tableAddChoose').bootstrapTable('getSelections');
	var count = $('#tableAddChoose').bootstrapTable('getData').length;
	var rowsfirst = $('#tableAddDetail').bootstrapTable('getData')
	var flog = false;
if(rows.length>0){
	for ( var i =0 ;i<rows.length;i++) {
		if(rowsfirst.length>0){
			for (var j =0 ;j<rowsfirst.length;j++) {
				if(rows[i].proname==rowsfirst[j].proname){
					alert("该商品已经存在,请重新选择!");
					return false;
				}else{
					flog=true;
				}
			}
		}else if(rowsfirst.length==0){	
			flog=true;
		}else{
			flog=false;
		}
	 if(flog == true){
		  		var proname = rows[i].proname;
		 		//var id = rows[i].id;
		 		var amount = rows[i].amount;
		 		var planAmount  = rows[i].planAmount;
		 		var price = rows[i].price;
		 		var completed = rows[i].completed;
		 		var pid = rows[i].pid;
		 		$('#tableAddDetail').bootstrapTable('insertRow', {
		 			index: count,
		 			row: {
		 				//id: id,
		 				pid: pid,
		 				proname: proname,
		 				planNo: rows.planNo,
		 				name:rows.name,
		 				deliverDateStr:rows.deliverDateStr,
		 				arriveDateStr:rows.arriveDateStr,
		 				productCode: rows.productCode,
		 				productType: rows.productType,
		 				specifications: rows.specifications,
		 				grade: rows.grade,
		 				units: rows.units,
		 				price: price,
		 				priceType: rows.priceType,
		 				amount: amount,
		 				roughWeight: rows.roughWeight,
		 				suttle: rows.suttle,
		 				comments: rows.comments,
		 				money:rows.money,
		 				planAmount: planAmount,
		 				completed: completed
		 			}
		 		});
	 }
	}
	}else{
		alert("请勾选商品!");
	}
	$('#purClose').click();
});
//保存
$("#AddPur-saveBtn").click(function () {
	//得到新增表格数据
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	var length = rows.length;
	console.log(rows);
	var params = getDataForAdd();
	for ( var i= 0 ;i<rows.length;i++) {
		var proname = rows[i].proname;
		var id = rows[i].id;
		var amount = rows[i].amount;
		var planAmount  = rows[i].planAmount;
		var price = rows[i].price;
		var completed = rows[i].completed;
		var pid = rows[i].pid;
		params.proname = proname;
		params.amount = amount;
		params.planAmount = planAmount;
		params.price = price;
		params.completed = completed;
	}
	
	
	if (length>0) {
		
		var flag = false;
		var flag = isMainNull(params);
		if (!flag) {
			//alert("请先输入数据");
			return;
		}
		var saleNo = $(info).attr('orderNo');
		params.orderNo = saleNo;
		params = JSON.stringify(params);
		console.log(params);
		//进货id是否绑定,没有id就新增
		var mainId = $('#mainId').val();
		if (saleNo == '' || saleNo == null || saleNo == undefined) {
			$.ajax({
				type: "post",
				url: DOMAIN + '/purchase/insertPurChaseList/' + isLogin,
				data: params,
				dataType: 'JSON',
				contentType: "application/JSON; charset=utf-8",
				success: function (result) {
					if (result.status == 200) {
						alert("保存成功");
						$("#table").bootstrapTable("refresh", {
							silent: true //静态刷新
						});
					}
				},
				error: function () {
					alert('保存失败');
				}
			});
			$('#main1')[0].reset();
			//$('#info')[0].reset();
			$('#mainId').val('');
			$('.close').click();
		} else {
			//更新
			$.ajax({
				type: "patch",
				url: DOMAIN + '/purchase/insertPurChaseListInfo/' + mainId + isLogin,
				data: params,
				dataType: 'JSON',
				contentType: "application/JSON; charset=utf-8",
				success: function (result) {
					if (result.status == 200) {
			
						alert("保存成功");
						$("#table").bootstrapTable("refresh", {
							silent: true //静态刷新
						});
					}
				},
				error: function () {
					alert('编辑失败');
				},
				complete: function () {
				}
			});
			$('#main1')[0].reset();
			//$('#info')[0].reset();
			$('#mainId').val('');
			$('.close').click();
			//将删除的id置空
			delId = [];
			saleNo = null;
			params.orderNo = null;
		}
	}else{
		alert("请选中需要下单的采购订单");
	}
});

//新增时获取数据的方法
function getDataForAdd() {
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	var params = {};

	params.orderType = $("#orderType").val();
	params.purchaseMan = $('#purchaseMan').val();
	params.deliverType = $('#deliverType').val();
	params.deliverDateStr = $('#deliverDateStr').val();
	params.arriveDateStr = $('#arriveDateStr').val();
	params.supplierCode = $('#supplierCode').val();
	params.currency = $('#currency').val();
	params.comments = $('#comments').val();
	params.purchaseCompany = $('#purchaseCompany').val();
	params.proname = $("#productName").val();
	params.price = $("#price").val();
	params.amount = $("#amount").val();
	params.address = $("#addresses").val();
	params.planAmount = $("#amount").val();
	params.rough_weight =  $("#roughWeight").val();
	params.suttle =  $("#suttle").val();
	params.money = $("#money").val();
	params.name = $("#names").val();
	params.planNo = $("#BigPlanNo").val();
	params.warehouseOutInfoList = rows;
	params.delId = delId;
	return params;
}

//删除选中行
$("#AddPur-deleteBtn").click(function () {
	var ids = $("#tableAddDetail").bootstrapTable('getSelections')
	if (ids == "" || ids == null) {
		alert("请选中一行");
	} else {
		for (var i = 0; i < ids.length; i++) {
			var pid = ids[i].pid;
			var id = ids[i].id;
			//如果是库中的数据会有id，按照id删除，否则按照序号删除

			if (id == "" || id == null) {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'pid', values: [pid] });
			} else {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'id', values: [id] });
				delId.push(id);
				}
		}

	}
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	var allmoney = 0;
				for (var i = 0;i<rows.length;i++) {
					allmoney += rows[i].money; 
				}	
	allmoney = allmoney.toFixed(2);
	allmoney = allmoney.toString();
	document.getElementById("moneynum").innerHTML=allmoney;
});

//删除选中行
$("#ChoosePur-deleteBtn").click(function () {
	var ids = $("#tableAddChoose").bootstrapTable('getSelections')
	if (ids == "" || ids == null) {
		alert("请选中一行");
	} else {
		for (var i = 0; i < ids.length; i++) {
			var pid = ids[i].pid;
			var id = ids[i].id;
			//如果是库中的数据会有id，按照id删除，否则按照序号删除

			if (id == "" || id == null) {
				$("#tableAddChoose").bootstrapTable('remove', { field: 'pid', values: [pid] });
			} else {
				$("#tableAddChoose").bootstrapTable('remove', { field: 'id', values: [id] });
				delId.push(id);
				}
		}

	}
});


function isMainNull(t) {
	if(t.planNo == '' || t.planNo ==null){
		alert("请选择采购计划");
		return false;
	}
	if(t.name == '' || t.name ==null){
		alert("请选择供货商");
		return false;
	}
	return true;
}
function isInfoNull(t) {

	if (t.productName == '' || t.productName == null) {
		alert("产品名称不能为空");
		return false;
	}
	if (t.price == '' || t.price < 0) {
		alert("商品单价必须大于零");
		return false;
	}
	if (t.priceType == '' || t.priceType == null) {
		alert("价格类型不能为空");
		return false;
	}
	if (t.suttle == '' || t.suttle < 0) {
		alert("产品净重必须大于零");
		return false;
	}
	return true;
}

//编辑信息
var info;
function EditInfo(e) {
	$("#info").css("display","block");
	$("#info-btn").css("display","block");
	var mstatus = $(e).attr('status');
	info = e;
	$('#tableAddDetail').bootstrapTable('removeAll');
	//将删除的id置空
	delId = [];
	function queryParamNew(params) {
		var params = {};
		return params;
	};
	var saleNo = $(e).attr('orderNo');
	var url = DOMAIN + '/purchase/queryPurchaseLists' + isLogin + '&saleNo=' + saleNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
	/* if(mstatus=='已取消'){
		alert("该订单已被取消,若要查看,请重新启用!");
		e=null;
		return false;
	}else{
		info = e;
		$('#tableAddDetail').bootstrapTable('removeAll');
		//将删除的id置空
		delId = [];
		function queryParamNew(params) {
			var params = {};
			return params;
		};
		var saleNo = $(e).attr('orderNo');
		var url = DOMAIN + '/purchase/queryPurchaseLists' + isLogin + '&saleNo=' + saleNo;
		$('#tableAddDetail').bootstrapTable(
			'refresh',
			{
				url: url,
				//查询参数
				queryParams: queryParamNew
			}
		);
		
	} */
	var rows = $('#tableAddDetail').bootstrapTable('getData');
		var allmoney = 0;
					for (var i = 0;i<rows.length;i++) {
						var money = parseFloat(rows[i].money);
						allmoney += money; 
					}
		allmoney = allmoney.toFixed(2);
		var allmoneystr = allmoney.toString();
	/* 	allmoneystr = allmoneystr.replace(/^0+/,""); */
	    document.getElementById("moneynum").innerHTML=allmoneystr;
	saleNo = null;
}

function lookInfo(e) {
	$("#info").css("display","none");
	$("#info-btn").css("display","none");
	var mstatus = $(e).attr('status');
	$('#tableAddDetail').bootstrapTable('removeAll');
	//将删除的id置空
	delId = [];
	var params = {};
	function queryParamNew(params) {
		return params;
	};
	var saleNo = $(e).attr('orderNo');
	var url = DOMAIN + '/purchase/queryPurchaseLists' + isLogin + '&saleNo=' + saleNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
	var rows = $('#tableAddDetail').bootstrapTable('getData');
		var allmoney = 0;
					for (var i = 0;i<rows.length;i++) {
						var money = parseFloat(rows[i].money);
						allmoney += money; 
					}
		allmoney = allmoney.toFixed(2);
		var allmoneystr = allmoney.toString();
	/* 	allmoneystr = allmoneystr.replace(/^0+/,""); */
	    document.getElementById("moneynum").innerHTML=allmoneystr;
	
}

function delInfo(e) {
	var r = confirm("确定删除该订单吗,删除之后数据将不能恢复？");
	var orderNo = $(e).attr('orderNo');
	var mstatus = $(e).attr('status');
	if (r) {
	    $.ajax({
	        type: "GET",
	        url: DOMAIN + '/purchase/deleteListPlan/' + isLogin + '&orderNo=' + orderNo,
	        cache: false,
	        async: false,
	        success: function (data) {
	            alert("删除成功！");
	            if($("#tableApproach")){
	            	$("#tableApproach").bootstrapTable("refresh", {
	                silent: true //静态刷新
	            });
	            }
	            $("#table").bootstrapTable("refresh", {
	                silent: true //静态刷新
	            });
	        },
	
	    });
	}
}

function sureInfo(e) {
	var r = confirm("确定该订单吗,确认之后数据将不能修改？");
	var orderNo = $(e).attr('orderNo');
	var mstatus = $(e).attr('status');
	if (r) {
	    $.ajax({
	        type: "GET",
	        url: DOMAIN + '/purchase/sureListPlan/' + isLogin + '&orderNo=' + orderNo,
	        cache: false,
	        async: false,
	        success: function (data) {
	            //alert("确认成功！");
	            if($("#tableApproach")){
	            	$("#tableApproach").bootstrapTable("refresh", {
	                silent: true //静态刷新
	            });
	            }
	            $("#table").bootstrapTable("refresh", {
	                silent: true //静态刷新
	            });
	        },
	
	    });
	}
	
}

function collbakeInfo(e) {
	var r = confirm("订单撤销后可以再次进行添加订单的操作!");
	var orderNo = $(e).attr('orderNo');
	var mstatus = $(e).attr('status');
	if (r) {
	   $.ajax({
	       type: "GET",
	       url: DOMAIN + '/purchase/collbackPlan/' + isLogin + '&orderNo=' + orderNo,
	       cache: false,
	       async: false,
	       success: function (data) {
	           alert("订单撤销成功！");
	           }
	  
	   	
	   });
	   window.location.reload();
	}
		
	
}

//新增前填写日期并获取批次号与进货编号
function resetTable() {
	// 将删除的id置空
	delId = [];
	$("#info").css("display","block");
	$("#info-btn").css("display","block");
	$('#main1')[0].reset();
	//$('#info')[0].reset();
	info="";
	time_rota($("#createTime"));
	time_rota($('#deliverDateStr'));
	time_rota($('#arriveDateStr'));
	$('#tableAddDetail').bootstrapTable('removeAll');
	var allmoney = 0.0;
	allmoney = allmoney.toFixed(2);
	document.getElementById("moneynum").innerHTML=allmoney;
	
}

function getFormJsonObject($form) {
	var unindexed_array = $form.serializeArray();
	var indexed_array = {};

	$.map(unindexed_array, function (n, i) {
		indexed_array[n['name']] = n['value'];
	});

	return indexed_array;
};

//计算行金额
function calc(){
		var r_price = $("#price").val();
		var r_amount = $("#amount").val();
		if(r_price != "" && r_price >0 && r_amount >0 && r_amount != ""){
			$("#money").val((r_price*r_amount).toFixed(2));
		}else{
			$("#money").val(0);
		}
	}

//下拉框填充
$(function () {
	
	loadTable();
	getSelList2($("#status"),"pur_status");
	getSelList($("#orderType"),"sale_order_type");
	getSelList($("#deliverType"),"deliver_type");
	getSelList($("#payType"),"count_way");
	
	$("#deliverType").on("change",function(){
		var deliver_type = $("#deliverType option:checked").html();
		if(deliver_type=="自提"){
			$("#addressDiv").css("display","none");
			$("#address").val("");
		}else{
			$("#addressDiv").css("display","block");
		}
	});
	
	$("#price").on("blur",function(){
		calc();
	});
	
	$("#amount").on("blur",function(){
		calc();
	});
	
	time_rota2($('#startTime'));
	time_rota($('#endTime'));
		//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.startTime = $("#startTime").val();
		params.endTime = $("#endTime").val();
		return params;
	};
	var url =DOMAIN + '/purchase/queryPurchaseList' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
})

//打开选择框时查询
$('#myModal').on('shown.bs.modal', function () {
	//getSelList($("#purchaseType1"), "/v1/purchaseType" + isLogin);
	$('#tableAddDetail').bootstrapTable(
		'refreshOptions',
		{
			//url: DOMAIN+'/v1/salesOrder'+isLogin,
		}
	);

})

//打开选择框时查询
$('#myModalChoose').on('shown.bs.modal', function () {
	//getSelList($("#purchaseType1"), "/v1/purchaseType" + isLogin);
	$('#tableAddDetail').bootstrapTable(
		'refreshOptions',
		{
			//url: DOMAIN+'/v1/salesOrder'+isLogin,
		}
	);

})

//关闭
$("#AddPur-closeBtn").click(function () {
	$("#close-btn").click();
})


$("#close-closeBtn").click(function () {
	$("#purClose").click();
})
var flag="";

function sign(){
	flag="customer";
}

function sign2(){
	flag="customerAdd";
}

var  planNo = null;
function selectLevelOne(row){

  $("#BigPlanNo").val(row.planNo);
  var dataList;
  planNo = row.planNo;
}
$("#ChoosePur-insertBtn").on("click", function() {
	$("#myModalChoose").modal("toggle");
	var url = DOMAIN + '/purchase/showPlanHtml' + isLogin + '&planNo=' + planNo;
	 $('#tableAddChoose').bootstrapTable(
	 	'refresh',
	 	{
	 		url: url,
	 		//查询参数
	 	}
	 );
})

function Selectspuler(row){
  $("#names").val(row.name);
  $("#addresses").val(row.address);
}

function selectProduct(row){
	$("#productName").val(row.name);
	$("#productCode").val(row.code);
	$("#productType").val(row.levelOneName + "/" + row.levelTwoName);
	$("#specifications").val(row.specifications);
	$("#grade").val(row.gradeName);
	$("#units").val(row.units);
}
